package com.xbongbong.crm.perform.query.list.button;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.parent.pojo.list.DataAnalysisListPojo;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.saas.enums.ListOptionEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.common.inject.Singleton;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 跟进记录
 * @author 吴峰
 * @date 2021/12/20 14:49
 */
@Component
public class CustomerCommunicate {

    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;

    private boolean enable;

    private Collection<Long> list;

    public boolean isEnable() {
        return enable;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    public Collection<Long> getList() {
        return list;
    }

    public void setList(Collection<Long> list) {
        this.list = list;
    }



    public CustomerCommunicate() {
        enable = false;
        list = new ArrayList<>();
    }

    public CustomerCommunicate(boolean enable, Collection<Long> list) {
        this.enable = enable;
        this.list = list;
    }

    /**
     * 客户跟进记录
     * @param dataAnalysisListPojo
     * @param alias
     * @param dataIdList
     * @param corpid
     * @param list
     * @return
     * @throws XbbException
     */
    public CustomerCommunicate getCommunicate(DataAnalysisListPojo dataAnalysisListPojo, String alias, List<Long> dataIdList, String corpid, List<FieldAttrEntity> list) throws XbbException {
        UserVO userVO = dataAnalysisListPojo.getUserVO();
        boolean enable = true;
        if (!Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(), dataAnalysisListPojo.getSubBusinessType())) {
            enable = userVO.getPermSet().contains(alias);
        }
        if (CollectionsUtil.isEmpty(dataIdList) || !enable) {
            return new CustomerCommunicate();
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery("data." + CustomerCommunicateEnum.CUSTOMER_NAME.getAttr()+".keyword", dataIdList));
        return get(boolQueryBuilder, dataAnalysisListPojo, CustomerCommunicateEnum.CUSTOMER_NAME.getAttr(), dataIdList, corpid, list);
    }

    /**
     * 线索跟进记录
     * @param dataAnalysisListPojo
     * @param alias
     * @param dataIdList
     * @param corpid
     * @param list
     * @return
     * @throws XbbException
     */
    public CustomerCommunicate getClueCommunicate(DataAnalysisListPojo dataAnalysisListPojo, String alias, List<Long> dataIdList, String corpid, List<FieldAttrEntity> list) throws XbbException {
        UserVO userVO = dataAnalysisListPojo.getUserVO();

        boolean enable = true;
        Integer businessType = dataAnalysisListPojo.getBusinessType();
        if ( !Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(), dataAnalysisListPojo.getSubBusinessType())) {
            enable = userVO.getPermSet().contains(alias);
        }
        if (CollectionsUtil.isEmpty(dataIdList) || !enable) {
            return new CustomerCommunicate();
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(CustomerCommunicateEnum.getEsAttr4Keyword(CustomerCommunicateEnum.COMMUNICATE_BUSINESS), dataIdList));
        boolQueryBuilder.filter(termQuery(CustomerCommunicateEnum.getEsAttr4Keyword(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE),businessType));
        return get(boolQueryBuilder, dataAnalysisListPojo, CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), dataIdList, corpid, list);
    }


    private CustomerCommunicate get(BoolQueryBuilder boolQueryBuilder, DataAnalysisListPojo dataAnalysisListPojo, String attr, List<Long> dataIdList, String corpid, List<FieldAttrEntity> list) throws XbbException {
        Set<Long> communicateList = new HashSet<>();
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termQuery("logType", 0));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getType()));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.collapse(new CollapseBuilder("data."+attr+".keyword"));
        sourceBuilder.query(boolQueryBuilder);
        //限定返回值
        sourceBuilder.fetchSource("data."+attr,null);
        //分页
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, dataIdList.size());
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);

        if(esEntities != null){
            List<PaasFormDataEntityExt> resultList = new ArrayList<>(esEntities.getContent());
            for (PaasFormDataEntityExt paasFormDataEntityExt : resultList) {
                JSONObject data = paasFormDataEntityExt.getData();
                if (Objects.nonNull(data) && Objects.nonNull(data.getLong(attr))) {
                    communicateList.add(data.getLong(attr));
                }
            }
        }
        FieldAttrEntity fieldFlow = new FieldAttrEntity();
        fieldFlow.setAttr(ListOptionEnum.FLOW.getAttr());
        fieldFlow.setAttrName(ListOptionEnum.FLOW.getAttrName());
        fieldFlow.setFieldType(FieldTypeEnum.FLOW.getType());
        fieldFlow.setDisableListSort(1);
        list.add(0, fieldFlow);
        return new CustomerCommunicate(true, communicateList);
    }

    public static void setCommunicateData(CustomerCommunicate followUpRecord, PaasFormDataEntityExt paasFormDataEntityExt) {
        if (followUpRecord.isEnable()) {
            JSONObject json = new JSONObject();
            Long dataId = paasFormDataEntityExt.getId();
            JSONObject data = paasFormDataEntityExt.getData();
            json.put("value", followUpRecord.getList().contains(dataId) ? 1 : 0);
            data.put(ListOptionEnum.FLOW.getAttr(), json);
        }
    }
}
